#include "types.h"
#include "defs.h"
#include "param.h"
#include "memlayout.h"
#include "mmu.h"
#include "proc.h"
#include "x86.h"
#include "syscall.h"
#include "stat.h"

//决定是否打印系统调用信息
#define TEST 0

// User code makes a system call with INT T_SYSCALL.
// System call number in %eax.
// Arguments on the stack, from the user call to the C
// library system call function. The saved user %esp points
// to a saved program counter, and then the first argument.

// Fetch the int at addr from the current process.
int
fetchint(uint addr, int *ip)
{
  struct proc *curproc = myproc();

  if(addr >= curproc->sz || addr+4 > curproc->sz)
    return -1;
  *ip = *(int*)(addr);
  return 0;
}

// Fetch the nul-terminated string at addr from the current process.
// Doesn't actually copy the string - just sets *pp to point at it.
// Returns length of string, not including nul.
int
fetchstr(uint addr, char **pp)
{
  char *s, *ep;
  struct proc *curproc = myproc();

  if(addr >= curproc->sz)
    return -1;
  *pp = (char*)addr;
  ep = (char*)curproc->sz;
  for(s = *pp; s < ep; s++){
    if(*s == 0)
      return s - *pp;
  }
  return -1;
}

// Fetch the nth 32-bit system call argument.
int
argint(int n, int *ip)
{
  return fetchint((myproc()->tf->esp) + 4 + 4*n, ip);
}

// Fetch the nth word-sized system call argument as a pointer
// to a block of memory of size bytes.  Check that the pointer
// lies within the process address space.
int
argptr(int n, char **pp, int size)
{
  int i;
  struct proc *curproc = myproc();
 
  if(argint(n, &i) < 0)
    return -1;
  if(size < 0 || (uint)i >= curproc->sz || (uint)i+size > curproc->sz)
    return -1;
  *pp = (char*)i;
  return 0;
}

// Fetch the nth word-sized system call argument as a string pointer.
// Check that the pointer is valid and the string is nul-terminated.
// (There is no shared writable memory, so the string can't change
// between this check and being used by the kernel.)
int
argstr(int n, char **pp)
{
  int addr;
  if(argint(n, &addr) < 0)
    return -1;
  return fetchstr(addr, pp);
}

extern int sys_chdir(void);
extern int sys_close(void);
extern int sys_dup(void);
extern int sys_exec(void);
extern int sys_exit(void);
extern int sys_fork(void);
extern int sys_fstat(void);
extern int sys_getpid(void);
extern int sys_kill(void);
extern int sys_link(void);
extern int sys_mkdir(void);
extern int sys_mknod(void);
extern int sys_open(void);
extern int sys_pipe(void);
extern int sys_read(void);
extern int sys_sbrk(void);
extern int sys_sleep(void);
extern int sys_unlink(void);
extern int sys_wait(void);
extern int sys_write(void);
extern int sys_uptime(void);
extern int sys_date(void);
extern int sys_dup2(void);
int
sys_alarm(void)
{
  int ticks;
  void (*handler)();
  if(argint(0, &ticks) < 0)
    return -1;
  if(argptr(1, (char **)&handler, sizeof(void *)) < 0)
    return -1;

  struct proc *p = myproc();
  p->alarmticks = ticks;
  p->alarmhandler = handler;
  p->alarmcounter = 0;

  return 0;
}

static int (*syscalls[])(void) = {
[SYS_fork]    sys_fork,
[SYS_exit]    sys_exit,
[SYS_wait]    sys_wait,
[SYS_pipe]    sys_pipe,
[SYS_read]    sys_read,
[SYS_kill]    sys_kill,
[SYS_exec]    sys_exec,
[SYS_fstat]   sys_fstat,
[SYS_chdir]   sys_chdir,
[SYS_dup]     sys_dup,
[SYS_getpid]  sys_getpid,
[SYS_sbrk]    sys_sbrk,
[SYS_sleep]   sys_sleep,
[SYS_uptime]  sys_uptime,
[SYS_open]    sys_open,
[SYS_write]   sys_write,
[SYS_mknod]   sys_mknod,
[SYS_unlink]  sys_unlink,
[SYS_link]    sys_link,
[SYS_mkdir]   sys_mkdir,
[SYS_close]   sys_close,
[SYS_date]    sys_date,
[SYS_dup2]    sys_dup2,
[SYS_alarm]   sys_alarm,
};

static char *syscall_names[] = {
  [SYS_fork]    "fork",
  [SYS_exit]    "exit",
  [SYS_wait]    "wait",
  [SYS_pipe]    "pipe",
  [SYS_read]    "read",
  [SYS_kill]    "kill",
  [SYS_exec]    "exec",
  [SYS_fstat]   "fstat",
  [SYS_chdir]   "chdir",
  [SYS_dup]     "dup",
  [SYS_getpid]  "getpid",
  [SYS_sbrk]    "sbrk",
  [SYS_sleep]   "sleep",
  [SYS_uptime]  "uptime",
  [SYS_open]    "open",
  [SYS_write]   "write",
  [SYS_mknod]   "mknod",
  [SYS_unlink]  "unlink",
  [SYS_link]    "link",
  [SYS_mkdir]   "mkdir",
  [SYS_close]   "close",
  [SYS_date]    "date",
  [SYS_dup2]    "dup2",
  [SYS_alarm]   "alarm",
};

// 打印系统调用参数的函数
void print_syscall_args(int num) {
    switch (num) {
        case SYS_fork:
            cprintf("(no args)");
            break;
        case SYS_exit: {
            int status;
            if (argint(0, &status) == 0) {
                cprintf("status=%d", status);
            }
            break;
        }
        case SYS_wait: {
            int *wstatus;
            if (argptr(0, (char **)&wstatus, sizeof(int)) == 0) {
                cprintf("wstatus=%p", wstatus);
            }
            break;
        }
        case SYS_pipe: {
            int *pipedes;
            if (argptr(0, (char **)&pipedes, 2 * sizeof(int)) == 0) {
                cprintf("pipedes=%p", pipedes);
            }
            break;
        }
        case SYS_read:
        case SYS_write: {
            int fd;
            char *buf;
            int n;
            if (argint(0, &fd) == 0 && argptr(1, &buf, 1) == 0 && argint(2, &n) == 0) {
                cprintf("fd=%d, buf=%p, n=%d", fd, buf, n);
            }
            break;
        }
        case SYS_kill: {
            int pid;
            if (argint(0, &pid) == 0) {
                cprintf("pid=%d", pid);
            }
            break;
        }
        case SYS_exec: {
            char *path;
            char **argv;
            if (argstr(0, &path) == 0 && argptr(1, (char **)&argv, sizeof(char *)) == 0) {
                cprintf("path='%s', argv=%p", path, argv);
            }
            break;
        }
        case SYS_fstat: {
            int fd;
            struct stat *st;
            if (argint(0, &fd) == 0 && argptr(1, (char **)&st, sizeof(struct stat)) == 0) {
                cprintf("fd=%d, st=%p", fd, st);
            }
            break;
        }
        case SYS_chdir: {
            char *path;
            if (argstr(0, &path) == 0) {
                cprintf("path='%s'", path);
            }
            break;
        }
        case SYS_dup: {
            int fd;
            if (argint(0, &fd) == 0) {
                cprintf("fd=%d", fd);
            }
            break;
        }
        case SYS_getpid:
            cprintf("(no args)");
            break;
        case SYS_sbrk: {
            int addr;
            if (argint(0, &addr) == 0) {
                cprintf("addr=%d", addr);
            }
            break;
        }
        case SYS_sleep: {
            int n;
            if (argint(0, &n) == 0) {
                cprintf("n=%d", n);
            }
            break;
        }
        case SYS_uptime:
            cprintf("(no args)");
            break;
        case SYS_open: {
            char *path;
            int mode;
            if (argstr(0, &path) == 0 && argint(1, &mode) == 0) {
                cprintf("path='%s', mode=%d", path, mode);
            }
            break;
        }
        case SYS_mknod: {
            char *path;
            int major;
            int minor;
            if (argstr(0, &path) == 0 && argint(1, &major) == 0 && argint(2, &minor) == 0) {
                cprintf("path='%s', major=%d, minor=%d", path, major, minor);
            }
            break;
        }
        case SYS_unlink: {
            char *path;
            if (argstr(0, &path) == 0) {
                cprintf("path='%s'", path);
            }
            break;
        }
        case SYS_link: {
            char *oldpath;
            char *newpath;
            if (argstr(0, &oldpath) == 0 && argstr(1, &newpath) == 0) {
                cprintf("oldpath='%s', newpath='%s'", oldpath, newpath);
            }
            break;
        }
        case SYS_mkdir: {
            char *path;
            if (argstr(0, &path) == 0) {
                cprintf("path='%s'", path);
            }
            break;
        }
        case SYS_close: {
            int fd;
            if (argint(0, &fd) == 0) {
                cprintf("fd=%d", fd);
            }
            break;
        }
        case SYS_date:
            cprintf("(no args)");
            break;
        case SYS_dup2: {
            int oldfd;
            int newfd;
            if (argint(0, &oldfd) == 0 && argint(1, &newfd) == 0) {
                cprintf("oldfd=%d, newfd=%d", oldfd, newfd);
            }
        }
        case SYS_alarm: {
            int ticks;
            void (*handler)();
            if (argint(0, &ticks) == 0 && argptr(1, (char **)&handler, sizeof(void *)) == 0) {
                cprintf("ticks=%d, handler=%p", ticks, handler);
            }
        }
        default:
            cprintf("(unknown args)");
            break;
    }
}

/**
 * @brief 打印系统调用的信息，并执行系统调用
 * 
 * 该函数根据传入的测试标志决定是否打印系统调用的详细信息，包括系统调用名称、参数和返回值。
 * 如果测试标志为真，则打印详细信息；否则，仅执行系统调用。
 * 
 * @param num 系统调用号，用于索引系统调用表和系统调用名称表
 * @param curproc 当前进程的结构体指针，用于获取进程信息和设置返回值
 */
void
print_syscall_msg(int num, struct proc *curproc){
    if(TEST){
        // 打印系统调用名称
        cprintf("%s -> ", syscall_names[num]);
        // 打印参数
        print_syscall_args(num);
        // 执行系统调用
        curproc->tf->eax = syscalls[num]();
        // 打印返回值
        cprintf(" -> %d\n", curproc->tf->eax);
    }else{
        // 执行系统调用
        curproc->tf->eax = syscalls[num]();
    }
}

void
syscall(void)
{
    int num;
    struct proc *curproc = myproc();

    num = curproc->tf->eax;
    if(num > 0 && num < NELEM(syscalls) && syscalls[num]) {
        print_syscall_msg(num, curproc);
    } else {
        cprintf("%d %s: unknown sys call %d\n",
                curproc->pid, curproc->name, num);
        curproc->tf->eax = -1;
    }
}
